#include "fileoperation.h"

#include <QJsonDocument>
#include <QJsonObject>
// 在头文件初始化会出现重复定义？
FileOperation* FileOperation::pSingleton = new FileOperation;

void FileOperation::writeConfig(fileConfig config)
{
    // 保存写入数据
    QJsonObject obj;
    obj.insert("IP", config.ip);
    obj.insert("PORT", config.port);
    obj.insert("USERNAME", config.username);
    obj.insert("PASSWORD", config.password);
    obj.insert("FILEPATH", FilePath);
    obj.insert("IS_SAVE", config.is_save_pwd);
    QJsonDocument doc(obj);
    QByteArray json = doc.toJson();
    QFile file(FilePath);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    file.write(json.data(), json.size());
    file.close();
}

bool FileOperation::readConif(fileConfig* config)
{
    if(isFile())
    {
        QFile file(FilePath);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray data = file.readAll();
        file.close();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject obj = doc.object();
        config->ip = obj.value("IP").toString();
        config->port = obj.value("PORT").toString();
        config->username = obj.value("USERNAME").toString();
        config->password = obj.value("PASSWORD").toString();
        config->filepath = obj.value("FILEPATH").toString();
        config->is_save_pwd = obj.value("IS_SAVE").toBool();
        return true;
    }
    return false;
}



bool isFile(const QString file)
{
    return QFile::exists(file);
}

